package com.liwenfeng.diancanspringboot.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.liwenfeng.diancanspringboot.common.constant.StatusConstant;
import com.liwenfeng.diancanspringboot.common.exception.DeletionNotAllowedException;
import com.liwenfeng.diancanspringboot.common.result.PageResult;
import com.liwenfeng.diancanspringboot.mapper.CategoryMapper;
import com.liwenfeng.diancanspringboot.mapper.DishMapper;
import com.liwenfeng.diancanspringboot.mapper.SetmealMapper;
import com.liwenfeng.diancanspringboot.pojo.dto.CategoryDTO;
import com.liwenfeng.diancanspringboot.pojo.dto.CategoryPageQueryDTO;
import com.liwenfeng.diancanspringboot.pojo.entity.Category;
import com.liwenfeng.diancanspringboot.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private DishMapper dishMapper;

    // 修改分类
    @Override
    public void update(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
    }

    // 分类分页查询
    @Override
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        Page<Category> page = categoryMapper.selectByPage(categoryPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    // 新增分类
    @Override
    public void save(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        category.setStatus(StatusConstant.DISABLE);
        categoryMapper.insert(category);
    }

    // 分类状态修改
    @Override
    public void changeStatus(Integer status, Long id) {
        Category category = new Category();
        category.setId(id);
        category.setStatus(status);
        categoryMapper.update(category);
    }

    // 删除分类
    @Override
    public void delete(Long id) {
        Integer count = dishMapper.countByCategoryId(id);
        if (count > 0) {
            // 当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException("当前分类下有菜品，不能删除");
        }
        count = setmealMapper.countByCategoryId(id);
        if (count > 0) {
            // 当前分类下有套餐，不能删除
            throw new DeletionNotAllowedException("当前分类下有套餐，不能删除");
        }
        categoryMapper.delete(id);
    }

    // 分类列表
    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);
    }
}
